package com.sinothk.special.buyer.userblog.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sinothk.special.buyer.userblog.entity.UserBlog;
import com.sinothk.special.buyer.userblog.entity.UserBlogCollector;
import com.sinothk.special.buyer.userblog.mapper.UserBlogCollectorMapper;
import com.sinothk.special.buyer.userblog.mapper.UserBlogMapper;
import com.sinothk.special.buyer.userblog.service.IUserBlogCollectorService;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.system.vo.LoginUser;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @Description: 个人博客收藏者
 * @Author: Liangyt
 * @Date:   2022-06-06
 * @Version: V1.0
 */
@Service
public class UserBlogCollectorServiceImpl extends ServiceImpl<UserBlogCollectorMapper, UserBlogCollector> implements IUserBlogCollectorService {

    @Resource
    private UserBlogMapper userBlogMapper;
    @Resource
    private UserBlogCollectorMapper userBlogCollectorMapper;

    @Override
    public void addCollectNum(String blogId) throws Exception {
        UserBlog userBlog = userBlogMapper.selectById(blogId);
        if (userBlog == null) throw new Exception("信息不存在");
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

        LambdaQueryWrapper<UserBlogCollector> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserBlogCollector::getBlogId, blogId).eq(UserBlogCollector::getUserId, loginUser.getId());
        UserBlogCollector userBlogCollectorDB = userBlogCollectorMapper.selectOne(wrapper);

        if (userBlogCollectorDB == null) {
            UserBlogCollector collector = new UserBlogCollector();
            collector.setBlogId(blogId);
            collector.setUserId(loginUser.getId());
            userBlogCollectorMapper.insert(collector);
        }else{
            userBlogCollectorMapper.deleteById(userBlogCollectorDB.getId());
        }
    }
}
